<?php

namespace Api\Model;

class CartModel extends BaseModel {

    /**
     * 添加商品到购物车
     */
    public function addToCart($userId) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $goodsId = I('goodsId', 0);
        if ($goodsId <= 0)
            return $rt;

        $m = M('shop_cart');
        $goodsInfo = $this->getGoodsInfo($goodsId);
        if (empty($goodsInfo)) {
            $rt['info'] = '此商品已经下架!';
            return $rt;
        }
        $inSource = $this->checkSource($userId, $goodsInfo);
        if ($inSource) {
            $rt['info'] = '商品无法购买!';
            return $rt;
        }
        $goodsInCart = $m->where('type = 0 and userId=' . $userId . ' AND goodsId=' . $goodsId)->find();
        if (empty($goodsInCart)) {
            if ($goodsInfo['goodsStock'] == 0) {
                $rt['info'] = '库存不足!';
                return $rt;
            }
            $goodsInfo['userId'] = $userId;
            $goodsInfo['goodsNumber'] = 1;
            $goodsInfo['createTime'] = date('Y-m-d H:i:s');
            unset($goodsInfo['goodsStock']);
            $rs = $m->add($goodsInfo);
            if ($rs === FALSE)
                return $rt;

            $rt['code'] = 1;
            $rt['info'] = 'Success!';
            return $rt;
        } else {
            if ($goodsInfo['goodsStock'] <= ($goodsInCart['goodsNumber'] + 1)) {
                $rt['info'] = '库存不足!';
                return $rt;
            }

            $rs = $m->where('cartId=' . $goodsInCart['cartId'])->setInc('goodsNumber');
            if ($rs === FALSE)
                return $rt;

            $rt['code'] = 1;
            $rt['info'] = 'Success!';
            return $rt;
        }
    }

    /**
     * 获取商品信息
     */
    public function getGoodsInfo($goodsId) {
        $sql = "SELECT g.goodsId,s.shopId,g.goodsName,g.goodsThumbs,g.marketPrice,g.goodsStock,g.shopPrice,s.shopName,g.goodsSize,g.goodsWeight,s.postage,g.isOffline,g.isSource "
                . "FROM __PREFIX__goods as g LEFT JOIN __PREFIX__shops as s ON g.shopId = s.shopId "
                . "WHERE goodsFlag=1 AND isSale=1 AND goodsStatus=1 AND isSelling = 1 AND isDel = 0 AND goodsId = " . $goodsId;
        $data = $this->queryRow($sql);

        return $data;
    }

    /**
     * 购物车列表
     * @param type $userId
     * @return type
     */
    public function getCartList($userId) {
//        $m = M('shop_cart');
//        $data = $m->where('type = 0 and userId=' . $userId)->select();
        $sql = "select sc.cartId,sc.userId,sc.shopId,g.goodsId,g.goodsName,g.goodsThumbs,g.marketPrice,g.shopPrice,sc.goodsNumber,sc.shopName,g.goodsSize,g.goodsWeight,g.isOffline,sc.createTime,sc.postage"
                . " from __PREFIX__shop_cart as sc left join __PREFIX__goods as g on sc.goodsId = g.goodsId where type = 0 and userId = " . $userId;
        $data = $this->query($sql);
        if (empty($data))
            return FALSE;

        $list = array();
        foreach ($data as $v) {
            $list['shop'][$v['shopId']]['shopName'] = $v['shopName'];
            $list['shop'][$v['shopId']]['postage'] = $v['postage'];
            $list['shop'][$v['shopId']]['goods'][] = $v;
            $list['shopPriceSum'] += ($v['shopPrice'] * $v['goodsNumber']);
            $list['postageSum'][$v['shopId']] = $v['postage'];
            $list['goodsSum'] += 1;
        }
        $temp = array();
        foreach ($list['shop'] as $v) {
            $temp[] = $v;
        }
        $list['shop'] = $temp;
        $list['postageSum'] = array_sum($list['postageSum']);
        $list['priceSum'] = $list['shopPriceSum'] + $list['postageSum'];

        return $list;
    }

    /**
     * 修改购物车中的商品数量
     * @return string
     */
    public function changeCartGoodsNum() {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $cartId = I('cartId', 0);
        $num = I('num', 0);
        if ($cartId <= 0)
            return $rt;
        if ($num == 0) {
            $rt['info'] = '商品数量不能少于1';
            return $rt;
        }
        $m = M('shop_cart');
        $cartGoods = $m->where('cartId=' . $cartId)->find();
        $goodsInfo = M('goods')->where('goodsId=' . $cartGoods['goodsId'])->find();
        if ($goodsInfo['goodsStock'] < $num) {
            $rt['info'] = '库存不足!';
            return $rt;
        }
        $rs = $m->where('cartId=' . $cartId)->save(array('goodsNumber' => $num));

        if ($rs === FALSE)
            return $rt;

        $rt['code'] = 1;
        $rt['info'] = 'Success!';
        return $rt;
    }

    /**
     * 删除购物车中的商品
     * @return type
     */
    public function delCartGoods() {
        $m = M('shop_cart');
        $cartId = I('cartId', 0);
        $rs = $m->where('cartId=' . $cartId)->delete();

        return $rs;
    }

    /**
     * 清空购物车中的商品
     * @return type
     */
    public function cleanCartGoods($userId) {
        $m = M('shop_cart');
        $rs = $m->where('userId=' . $userId)->delete();

        return $rs;
    }

    /**
     * 检查购物车是否有相同源头的产品
     * @param type $userId
     * @param type $goodsId
     * @return boolean
     */
    protected function checkSource($userId, $goodsInfo) {
        $m = M('shop_cart');
        $goodsInCart = $m->where('type = 0 and userId=' . $userId)->select();
        if(empty($goodsInCart))
            return FALSE;
        $goodsIds = array();
        foreach($goodsInCart as $v) {
            $goodsIds[] = $v['goodsId'];
        }
        if(in_array($goodsInfo['goodsId'], $goodsIds)) {
            return FALSE;
        }
        $sourceInCart = M('goods_resale')->where('goodsId in (' . implode('m', $goodsIds) . ')')->select();
        if(empty($sourceInCart))
            return FALSE;
        $sourceIds = array();
        foreach ($sourceInCart as $v) {
            $sourceIds[] = $v['sourceId'];
        }
        if($goodsInfo['isSource']) {
            if(in_array($goodsInfo['goodsId'], $sourceIds)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            $sourceId = M('goods_resale')->where('goodsId = ' . $goodsInfo['goodsId'])->getField('sourceId');
            if(in_array($sourceId, $sourceIds)) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
    }

}
